package com.myway.front.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.myway.front.dao.TabUserInfoMapper;
import com.myway.front.msmUtil.SmsDemo;
import com.myway.front.pojo.TabUserInfo;
import com.myway.front.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private TabUserInfoMapper tabUserInfoMapper;
    /**
     * 发送短息验证码
     * @param phoneNumber
     * @param request
     * @return
     */
    @Override
    public String getCode(String phoneNumber, HttpServletRequest request) {
        SmsDemo sd = new SmsDemo();
        String code = (int)((Math.random()*9+1)*100000)+"";
        request.getSession().setAttribute("code",code);
        try {
            SendSmsResponse response =  sd.sendSms(phoneNumber,code);
            return response.getCode();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return "Nok";

    }

    /**
     * 手机短息验证码验证登陆
     * @param phoneNumber
     * @param code
     * @param request
     * @return
     */
    @Override
    public String phoneLogin(String phoneNumber, String code, HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(session.getAttribute("code").equals(code)){
            session.removeAttribute("code");
            TabUserInfo tuf = new TabUserInfo();
            tuf.setUserPhoneNum(phoneNumber);
            tuf.setUserId(code);
            tabUserInfoMapper.insert(tuf);
            return "ok";
        }else{
            session.removeAttribute("code");
            return "Nok";
        }
    }

}
